// utils/http.js

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
    this.interceptors = {
      request: null,
      response: null
    }
  }
  
  // 设置请求拦截器
  setRequestInterceptor(interceptor) {
    this.interceptors.request = interceptor
  }
  
  // 设置响应拦截器
  setResponseInterceptor(interceptor) {
    this.interceptors.response = interceptor
  }
  
  request(options) {
    return new Promise((resolve, reject) => {
      // 请求拦截
      if (this.interceptors.request) {
        options = this.interceptors.request(options) || options
      }
      
      // 合并header
      const header = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + uni.getStorageSync('token') || '',
        ...options.header
      }
      
      uni.request({
        url: this.baseUrl + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header,
        success: (res) => {
          // 响应拦截
          if (this.interceptors.response) {
            res = this.interceptors.response(res) || res
          }
          
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }
  
  get(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data,
      ...options
    })
  }
  
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }
  
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }
  
  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data,
      ...options
    })
  }
}

// 创建实例
const http = new HttpRequest('http://localhost:8080')

// 设置请求拦截器
http.setRequestInterceptor((config) => {
  // 可以在这里添加全局请求参数
  console.log('请求拦截:', config)
  return config
})

// 设置响应拦截器
http.setResponseInterceptor((response) => {
  console.log('响应拦截:', response)
  // 统一处理错误码
  if (response.statusCode !== 200) {
    uni.showToast({
      title: response.data.message || '请求错误',
      icon: 'none'
    })
    
    if (response.statusCode === 401) {
      // 跳转登录
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }
  }
  return response
})

export default http